package 题目集.bfs;

import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Scanner;

/**
 * https://ac.nowcoder.com/acm/contest/82672/A
 */
public class A寻径指津 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        char[][] maze = new char[n][m];
        boolean[][] vis = new boolean[n][m];
        int sx = 0, sy = 0, tx = 0, ty = 0;
        sc.nextLine();
        for (int i = 0; i < n; i++) {
            String line = sc.nextLine();
            for (int j = 0; j < m; j++) {
                maze[i][j] = line.charAt(j);
                if (maze[i][j] == 'S') {
                    sx = i;
                    sy = j;
                } else if (maze[i][j] == 'T') {
                    tx = i;
                    ty = j;
                }
            }
        }
        Queue<int[]> queue = new ArrayDeque<>();
        queue.add(new int[]{sx, sy});
        vis[sx][sy] = true;
        int step = 0;
        int[][] dirs = new int[][]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        boolean flag = false;
        out:
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                int[] curr = queue.poll();
                int x = curr[0], y = curr[1];
                if (x == tx && y == ty) {
                    flag = true;
                    break out;
                }
                for (int[] dir : dirs) {
                    int nx = dir[0] + x;
                    int ny = dir[1] + y;
                    for (; nx >= 0 && nx < n && ny >= 0 && ny < m && maze[nx][ny] != '#'; nx += dir[0], ny += dir[1]) {
                    }
                    nx -= dir[0];
                    ny -= dir[1];
                    if (!vis[nx][ny]) {
                        queue.add(new int[]{nx, ny});
                        vis[nx][ny] = true;
                    }
                }
            }
            step++;
        }
        System.out.println(flag ? step : -1);
    }
}
